import React, { Component } from 'react'
import { Table, Space, Form, message, Tooltip, Input, InputNumber } from 'antd'
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  DeleteFilled,
  RightOutlined,
  DownOutlined,
} from '@ant-design/icons'
import NewModal from '../../componentJsx/common/NewModal'
import HasPermi from '../../componentJsx/common/hasPermi'
import 'antd/dist/antd.css'
import '../../componentCss/component.css'
import {
  getConfigurationData,
  addConfigurationData,
  editConfigurationData,
  deleteConfigurationData,
} from '../../api2'
import 'moment/locale/zh-cn'
class Index extends Component {
  constructor(props) {
    super(props)
    this.state = {
      deleteModalVisible: false, //删除的模态框
      modifyModalVisible: false, //修改的模态框
      addModalVisible: false, //添加编码的模态框
      addParentModalVisible: false, //添加父项的模态框
      confirmLoading: false, //确认按钮异步等待
      tableLoading: false,
      selectedRow: {
        //选中行的数据
        id: null,
        key: null,
        code: null,
        name: null,
        description: null,
        parentId: null,
        sort: null,
      },
      //表格数据
      tableData: [],
      //表格列
      tableColumns: [
        {
          title: '编码',
          dataIndex: 'code',
          key: 'code',
          width: 200,
          render: (text, record) =>
            this.state.tableData.indexOf(record) >= 0 || record.children ? (
              <strong>{text}</strong>
            ) : (
              <>{text}</>
            ),
        },
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name',
          width: '20%',
          render: (text, record) =>
            this.state.tableData.indexOf(record) >= 0 || record.children ? (
              <strong>{text}</strong>
            ) : (
              <>{text}</>
            ),
        },
        {
          title: '描述',
          dataIndex: 'description',
          width: '30%',
          key: 'description',
          render: (text, record) =>
            this.state.tableData.indexOf(record) >= 0 || record.children ? (
              <strong>{text}</strong>
            ) : (
              <>{text}</>
            ),
        },
        {
          title: '排序',
          dataIndex: 'sort',
          width: 100,
          key: 'sort',
          render: (text, record) =>
            this.state.tableData.indexOf(record) >= 0 || record.children ? (
              <strong>{text}</strong>
            ) : (
              <>{text}</>
            ),
        },
        {
          title: '操作',
          dataIndex: 'handle',
          width: 150,
          align: 'center',
          render: (_, record) =>
            this.state.tableData.indexOf(record) >= 0 ? (
              <Space>
                <Tooltip title="删除">
                  <div>
                    <HasPermi
                      bottonData={{
                        type: 'link',
                        interceptor: 'tmfs:configuration:del',
                        icon: <DeleteOutlined />,
                        clickFn: () => this.showModal('delete', record),
                      }}
                    />
                  </div>
                </Tooltip>
                <Tooltip title="修改">
                  <div>
                    {' '}
                    <HasPermi
                      bottonData={{
                        type: 'link',
                        interceptor: 'tmfs:configuration:edit',
                        icon: <EditOutlined />,
                        clickFn: () => this.showModal('modify', record),
                      }}
                    />
                  </div>
                </Tooltip>
                <Tooltip title="添加枚举值">
                  <div>
                    <HasPermi
                      bottonData={{
                        type: 'link',
                        interceptor: 'tmfs:configuration:add',
                        icon: <PlusOutlined />,
                        clickFn: () => this.showModal('add', record),
                      }}
                    />
                  </div>
                </Tooltip>
              </Space>
            ) : (
              <Space>
                <Tooltip title="删除">
                  <div>
                    <HasPermi
                      bottonData={{
                        type: 'link',
                        interceptor: 'tmfs:configuration:del',
                        icon: <DeleteOutlined />,
                        clickFn: () => this.showModal('delete', record),
                      }}
                    />
                  </div>
                </Tooltip>
                <Tooltip title="修改">
                  <div>
                    <HasPermi
                      bottonData={{
                        type: 'link',
                        interceptor: 'tmfs:configuration:edit',
                        icon: <EditOutlined />,
                        clickFn: () => this.showModal('modify', record),
                      }}
                    />
                  </div>
                </Tooltip>
              </Space>
            ),
        },
      ],
    }
  }
  modifyFormRef = React.createRef() //绑定修改信息表单
  addFormRef = React.createRef() //绑定新增编码表单
  addParentFormRef = React.createRef() //绑定新增父项表单
  //获取表格数据
  getData = (page, pageSize) => {
    let data = {
      limit: 1,
      pageSize: 999,
    }
    //发起请求
    this.setState({ tableLoading: true })
    getConfigurationData(data)
      .then((res) => {
        if (res.data.code === 200) {
          let data = res.data.data.list
          for (const item of data) {
            item.key = item.id
            if (item.children.length > 0) {
              for (const i of item.children) {
                i.key = i.id
              }
            } else {
              delete item.children
            }
          }
          this.setState({
            tableData: data,
            tableLoading: false,
          })
        } else {
          this.setState({ tableLoading: false })
          message.error(res.data.message || '数据加载失败')
        }
      })
      .catch((error) => {
        this.setState({ tableLoading: false })
        message.error('数据加载失败')
      })
  }
  //隐藏模态框
  hiddenModal = () => {
    this.setState({
      modifyModalVisible: false, //修改的模态框
      addModalVisible: false, //添加编码的模态框
      addParentModalVisible: false, //添加父项的模态框
      deleteModalVisible: false, //删除的模态框
      confirmLoading: false, //确认按钮异步等待
      selectedRow: {
        id: null,
        key: null,
        code: null,
        name: null,
        description: null,
        parentId: null,
        sort: null,
      },
    })
  }
  //显示表单模态框 name:模态框名; record:行数据
  showModal = (name, record) => {
    this.setState(
      {
        selectedRow: record,
        deleteModalVisible: name == 'delete' ? true : false,
        modifyModalVisible: name == 'modify' ? true : false,
        addModalVisible: name == 'add' ? true : false,
        addParentModalVisible: name == 'addParent' ? true : false,
      },
      () => {
        //填充当前选中行的数据
        if (name === 'modify')
          this.modifyFormRef.current.setFieldsValue(this.state.selectedRow)
      }
    )
  }
  //确定添加父项
  handleAddParent = () => {
    let formData = this.addParentFormRef.current.getFieldsValue()
    //表单验证
    this.addParentFormRef.current.validateFields().then((values, error) => {
      if (error) return
      this.setState({ confirmLoading: true })
      let sort
      if (formData.sort) {
        sort = formData.sort
      } else {
        sort = 0
      }
      let data = {
        code: formData.code,
        name: formData.name,
        description: formData.description,
        sort: sort,
      }
      //发起请求
      addConfigurationData(data)
        .then((res) => {
          if (res.data.code === 200) {
            this.getData()
            this.hiddenModal()
            message.success('已添加！')
          } else {
            message.error(res.data.message || '添加失败')
          }
        })
        .catch((error) => {
          message.error('添加失败')
        })
    })
  }
  //确定添加编码
  handleAdd = () => {
    let formData = this.addFormRef.current.getFieldsValue()
    this.addFormRef.current.validateFields().then((values, error) => {
      if (error) return
      let sort
      if (formData.sort) {
        sort = formData.sort
      } else {
        sort = 0
      }
      this.setState({ confirmLoading: true })
      let data = {
        code: formData.code,
        name: formData.name,
        description: formData.description,
        parentId: this.state.selectedRow.id,
        sort: sort,
      }
      addConfigurationData(data)
        .then((res) => {
          if (res.data.code === 200) {
            this.getData()
            this.hiddenModal()
            message.success('已添加！')
          } else {
            message.error(res.data.message || '添加失败')
          }
        })
        .catch((error) => {
          message.error('添加失败')
        })
    })
  }
  //确认修改信息
  handleModify = () => {
    let formData = this.modifyFormRef.current.getFieldsValue()
    this.modifyFormRef.current.validateFields().then((values, error) => {
      if (error) return
      this.setState({ confirmLoading: true })
      let sort
      if (formData.sort) {
        sort = formData.sort
      } else {
        sort = 0
      }
      let data = {
        code: this.state.selectedRow.code,
        description: formData.description,
        id: this.state.selectedRow.id,
        name: formData.name,
        parentId: this.state.selectedRow.parentId,
        sort: sort,
      }
      editConfigurationData(data)
        .then((res) => {
          if (res.data.code === 200) {
            this.getData()
            this.hiddenModal()
            message.success('已修改！')
          } else {
            message.error(res.data.message || '修改失败！')
          }
        })
        .catch((err) => {
          message.error('修改失败！')
        })
    })
  }
  //确定删除
  handleDelete = () => {
    this.setState({ confirmLoading: true })
    deleteConfigurationData(this.state.selectedRow.id)
      .then((res) => {
        if (res.data.code === 200) {
          this.getData()
          this.hiddenModal()
          message.success('删除成功！')
        } else {
          message.error(res.data.message || '删除失败！')
        }
      })
      .catch((err) => {
        message.error('删除失败！')
      })
  }
  //修改展开图标
  expandIcon = ({ expanded, onExpand, record }) => {
    if (record.children) {
      //可以展开
      if (expanded) {
        //展开
        return <DownOutlined />
      } else {
        //关闭
        return <RightOutlined />
      }
    } else {
      //不能展开
      return <span style={{ marginRight: 14 }}></span>
    }
  }
  componentWillMount() {
    //获取全部数据
    this.getData(1, 1000)
  }
  componentDidMount() {}
  //组件销毁时取消setState
  componentWillUnmount() {
    this.setState = (state, callback) => {
      return
    }
  }
  render() {
    return (
      <div>
        <div
          style={{
            margin: 10,
            borderRadius: 8,
            marginTop: 0,
            padding: 20,
            backgroundColor: '#fff',
          }}
        >
          <Tooltip title="添加枚举类型">
            <HasPermi
              bottonData={{
                type: 'primary',
                interceptor: 'tmfs:configuration:add',
                icon: <PlusOutlined />,
                clickFn: () =>
                  this.showModal('addParent', this.state.selectedRow),
                text: '新增',
              }}
            />
          </Tooltip>
          {/* 表格 */}
          <Table
            scroll={{ y: 'calc(100vh - 250px)' }}
            loading={this.state.tableLoading}
            style={{ marginTop: 10 }}
            columns={this.state.tableColumns}
            dataSource={this.state.tableData}
            pagination={false}
            bordered
          ></Table>
        </div>
        {/* 删除提示模态框 */}
        <NewModal
          modalOptions={{
            width: '400px',
            title: '删除提示',
            onCancel: this.hiddenModal,
            visible: this.state.deleteModalVisible,
          }}
          buttonOptions={{
            position: 'right',
            btnList: [
              {
                key: 1,
                onClick: this.hiddenModal,
                text: '取消',
              },
              {
                key: 0,
                onClick: this.handleDelete,
                text: '确认删除',
                type: 'primary',
                loading: this.state.confirmLoading,
              },
            ],
          }}
        >
          <DeleteFilled
            style={{
              fontSize: '28px',
              color: '#e00',
              float: 'left',
              backgroundColor: '#f002',
              padding: 8,
              borderRadius: '50%',
            }}
          />
          <div style={{ fontSize: 14, marginLeft: 60, fontWeight: 700 }}>
            删除{this.state.selectedRow.code}？
            <p style={{ color: 'red' }}>删除后数据不可恢复，请谨慎操作！</p>
          </div>
        </NewModal>
        {/* 修改数据模态框 */}
        <NewModal
          modalOptions={{
            width: '400px',
            title: '修改',
            forceRender: true,
            onCancel: this.hiddenModal,
            visible: this.state.modifyModalVisible,
          }}
          buttonOptions={{
            position: 'center',
            btnList: [
              {
                key: 0,
                onClick: this.handleModify,
                text: '确认',
                type: 'primary',
                loading: this.state.confirmLoading,
              },
              {
                key: 1,
                onClick: this.hiddenModal,
                text: '取消',
              },
            ],
          }}
        >
          <Form
            name="modifyForm"
            ref={this.modifyFormRef}
            labelCol={{ span: 4, offset: 0 }}
          >
            <Form.Item label="编码">{this.state.selectedRow.code}</Form.Item>
            <Form.Item
              label="名称"
              name="name"
              rules={[
                { required: true, message: '请输入名称!' },
                { max: 50, message: '名称不能大于50个字符' },
              ]}
            >
              <Input maxLength={50}></Input>
            </Form.Item>
            <Form.Item
              label="排序"
              name="sort"
              rules={[
                {
                  pattern: new RegExp(/^[0-9]\d*$/, 'g'),
                  message: '请输入大于等于0的整数',
                },
              ]}
            >
              <InputNumber
                min={0}
                style={{
                  width: '100%',
                }}
                maxLength={10}
              />
            </Form.Item>
            <Form.Item
              label="描述"
              name="description"
              rules={[{ max: 100, message: '描述不能大于100个字符' }]}
            >
              <Input maxLength={100} />
            </Form.Item>
          </Form>
        </NewModal>
        {/* 新增编码模态框 */}
        <NewModal
          modalOptions={{
            width: '400px',
            title: '新增',
            destroyOnClose: true,
            onCancel: this.hiddenModal,
            visible: this.state.addModalVisible,
          }}
          buttonOptions={{
            position: 'center',
            btnList: [
              {
                key: 0,
                onClick: this.handleAdd,
                text: '确认',
                type: 'primary',
                loading: this.state.confirmLoading,
              },
              {
                key: 1,
                onClick: this.hiddenModal,
                text: '取消',
              },
            ],
          }}
        >
          <Form
            name="addForm"
            ref={this.addFormRef}
            labelCol={{ span: 4, offset: 0 }}
          >
            <Form.Item
              label="编码"
              name="code"
              rules={[
                { required: true, message: '请输入编码值' },
                { max: 20, message: '编码不能大于20个字符' },
              ]}
            >
              <Input maxLength={20}></Input>
            </Form.Item>
            <Form.Item
              label="名称"
              name="name"
              rules={[
                { required: true, message: '请输入名称' },
                { max: 50, message: '名称不能大于50个字符' },
              ]}
            >
              <Input maxLength={50}></Input>
            </Form.Item>
            <Form.Item
              label="排序"
              name="sort"
              rules={[
                {
                  pattern: new RegExp(/^[0-9]\d*$/, 'g'),
                  message: '请输入大于等于0的整数',
                },
              ]}
            >
              <InputNumber
                maxLength={10}
                min={0}
                style={{
                  width: '100%',
                }}
              />
            </Form.Item>
            <Form.Item
              label="描述"
              name="description"
              rules={[{ max: 100, message: '描述不能大于100个字符' }]}
            >
              <Input maxLength={100}></Input>
            </Form.Item>
          </Form>
        </NewModal>

        {/* 新增父项模态框 */}
        <NewModal
          modalOptions={{
            width: '400px',
            title: '新增',
            destroyOnClose: true,
            onCancel: this.hiddenModal,
            visible: this.state.addParentModalVisible,
          }}
          buttonOptions={{
            position: 'center',
            btnList: [
              {
                key: 0,
                onClick: this.handleAddParent,
                text: '确认',
                type: 'primary',
                loading: this.state.confirmLoading,
              },
              {
                key: 1,
                onClick: this.hiddenModal,
                text: '取消',
              },
            ],
          }}
        >
          <Form
            name="addForm"
            ref={this.addParentFormRef}
            labelAlign="right"
            labelCol={{ span: 4, offset: 0 }}
          >
            <Form.Item
              label="编码"
              name="code"
              rules={[
                { required: true, message: '请输入编码值' },
                { max: 20, message: '编码不能大于20个字符' },
              ]}
            >
              <Input maxLength={20}></Input>
            </Form.Item>
            <Form.Item
              label="名称"
              name="name"
              rules={[
                { required: true, message: '请输入名称' },
                { max: 50, message: '名称不能大于50个字符' },
              ]}
            >
              <Input maxLength={50}></Input>
            </Form.Item>
            <Form.Item
              label="排序"
              name="sort"
              rules={[
                {
                  pattern: new RegExp(/^[0-9]\d*$/, 'g'),
                  message: '请输入大于等于0的整数',
                },
              ]}
            >
              <InputNumber
                maxLength={10}
                min={0}
                style={{
                  width: '100%',
                }}
              />
            </Form.Item>
            <Form.Item
              label="描述"
              name="description"
              rules={[{ max: 100, message: '描述不能大于100个字符' }]}
            >
              <Input maxLength={100}></Input>
            </Form.Item>
          </Form>
        </NewModal>
      </div>
    )
  }
}
export default Index
